package chapter05;

import org.junit.Test;

import java.util.concurrent.TimeUnit;

/**
 * synchronize 实现线程同步的弊端
 * 1）无法控制线程的阻塞时长
 * 2）线程阻塞是不能被中断的
 *
 * @author chisheng
 * @since 2021-11-07
 */
public class SynchronizedDefect {

    public synchronized void synMethod() {
        try {
            TimeUnit.HOURS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 1）无法控制线程的阻塞时长
     */
    @Test
    public void test01() throws InterruptedException {
        SynchronizedDefect synchronizedDefect = new SynchronizedDefect();
        new Thread(synchronizedDefect::synMethod, "thread01").start();

        // 保证 thread01 线程在 thread02 线程之前得到 CPU 资源
        TimeUnit.MILLISECONDS.sleep(2);

        // thread02 线程必须等待 thread01 线程释放锁后才能被运行
        new Thread(synchronizedDefect::synMethod, "thread02").start();
    }

    /**
     * 2）线程阻塞是不可中断的
     */
    @Test
    public void test02() throws InterruptedException {
        SynchronizedDefect synchronizedDefect = new SynchronizedDefect();
        new Thread(synchronizedDefect::synMethod, "thread01").start();

        // 保证 thread01 线程在 thread02 线程之前得到 CPU 资源
        TimeUnit.MILLISECONDS.sleep(2);

        Thread thread02 = new Thread(synchronizedDefect::synMethod, "thread02");
        thread02.start();
        // 保证 thread02 线程得到调度
        TimeUnit.MILLISECONDS.sleep(2);
        // 尝试中断线程 thread02
        thread02.interrupt();
        // 获取 thread02 线程的信息
        System.out.println(thread02.isInterrupted());
        System.out.println(thread02.getState());
    }

}
